package com.baixun.gassystem.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baixun.gascommon.config.ApiConfig;
import com.baixun.gasentity.entity.Point;
import com.baixun.gasentity.entity.SysVideoMessage;
import com.baixun.gassystem.mapper.PointMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: 上海燃气驾驶舱
 * @description: 首页需要获取的接口
 * @author: yesong
 **/
@Service
public class HomePageService {

    @Autowired
    private PointMapper pointMapper;


    /**
     * 生成鉴权头参数
     * @param accessKey 填写您的Access Key
     * @param secretKey 填写您的Secret Key
     * @param uri 填写请求的URI
     * @return 返回header鉴权参数
     */
    public static Map<String, String> buildAuthHeaderParams(String accessKey, String secretKey, String uri) {
        accessKey="ekpqcprab49rhfngp7m8";
        secretKey="ekpqywgm10u8api1dh1d";
        Map<String, String> params = new HashMap<>();
        // 鉴权过期时间，单位毫秒，请根据实际进行修改
        String expire = String.valueOf(System.currentTimeMillis() + 1800000);
        String input = String.format("%s;%s;%s;%s", accessKey, secretKey, expire, uri);

        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        String authToken;
        try {
            Mac mac = Mac.getInstance(secretKeySpec.getAlgorithm());
            mac.init(secretKeySpec);
            byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
            mac.update(inputBytes, 0, inputBytes.length);
            authToken = new String(Hex.encodeHex(mac.doFinal()));
        } catch (NoSuchAlgorithmException | InvalidKeyException ex) {
            throw new IllegalArgumentException(ex);
        }

        // key: header key   val: header value
        params.put("x-bce-evs-auth-user", accessKey);
        params.put("x-bce-evs-auth-expire-date", expire);
        params.put("x-bce-evs-auth-token", authToken);
        System.out.println("header params: " + params);
        return params;
    }

    /**
     * 获取配置算法点位数量
     * @return
     */
    public int getsuanfa(){
        int totalDataCount = 0;

        // 查询所有 pointId

        List<Object> pointIds = pointMapper.selectObjs(); // 获取所有 pointId

        // 遍历每个 pointId 并请求 API 获取数据
        for (Object pointId : pointIds) {
            try {
                // 初始化 ApiConfig 实例和请求 URL

                String url = ApiConfig.DOMAIN + "/api/v2/ai/apps/points/" + pointId + "/abilities";

                // 生成认证头
                Map<String, String> headerParams = buildAuthHeaderParams("accessKey", "secretKey", "/api/v2/ai/apps/points/"+pointId+"/abilities");

                // 创建 HTTP 连接
                HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
                con.setRequestMethod("GET");

                // 设置请求头
                for (Map.Entry<String, String> headerParamEntry : headerParams.entrySet()) {
                    con.setRequestProperty(headerParamEntry.getKey(), headerParamEntry.getValue());
                }

                // 获取响应码并检查请求是否成功
                int responseCode = con.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 读取响应数据
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    // 使用 FastJSON 解析 JSON 响应
                    JSONArray jsonArray = JSON.parseArray(response.toString());

                    // 累加返回的数据条数
                    totalDataCount += jsonArray.size();

                } else {
                    System.out.println("请求失败，响应码: " + responseCode + "，pointId: " + pointId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println("总数据条数: " + totalDataCount);
        return totalDataCount; // 返回所有 pointId 的总数据条数
    }


    /**
     * 获取实时监控数据
     * @return
     */
    public Map<String,Map<String,List<String>>> getVideo(){
        Map<String, Map<String, List<String>>> pointVideoLinks = new HashMap<>();

        // 查询所有 pointId
        QueryWrapper<Point> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("pointId");
        List<Object> pointIds = pointMapper.selectObjs(queryWrapper); // 从数据库获取所有 pointId

        // 固定 protocol 为 "rtmp"
        String protocol = "rtmp";

        // 遍历每个 pointId 并请求 API 获取视频链接
        for (Object pointIdObj : pointIds) {
            String pointId = pointIdObj.toString();
            try {
                String url ="https://evsretail.bce.baidu.com/api/v2/points/"+pointId+"/signed_url?protocol=rtmp";

                // 生成认证头
                Map<String, String> headerParams = buildAuthHeaderParams("accessKey", "secretKey", "/api/v2/points/"+pointId+"/signed_url");

                // 创建 HTTP 连接
                HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
                con.setRequestMethod("GET");

                // 设置请求头
                for (Map.Entry<String, String> headerParamEntry : headerParams.entrySet()) {
                    con.setRequestProperty(headerParamEntry.getKey(), headerParamEntry.getValue());
                }

                // 获取响应码并检查请求是否成功
                int responseCode = con.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 读取响应数据
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    // 解析 JSON 响应
                    JSONObject jsonResponse = JSON.parseObject(response.toString());

                    // 获取播放链接数组
                    List<String> urls = jsonResponse.getJSONArray("urls").toJavaList(String.class);
                    List<String> mainUrls = jsonResponse.getJSONArray("mainUrls").toJavaList(String.class);
                    List<String> subUrls = jsonResponse.getJSONArray("subUrls").toJavaList(String.class);

                    // 将数据存入结果映射
                    Map<String, List<String>> links = new HashMap<>();
                    links.put("urls", urls);
                    links.put("mainUrls", mainUrls);
                    links.put("subUrls", subUrls);
                    pointVideoLinks.put(pointId, links);

                } else {
                    System.out.println("请求失败，响应码: " + responseCode + "，pointId: " + pointId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return pointVideoLinks; // 返回所有点位的链接数据
    }


    /**
     * 根据点位获取视频播放链接
     * @param pointId
     * @return
     */
    public Map<String,Map<String,List<String>>> getVideoById(Long pointId){

        Map<String, Map<String, List<String>>> pointVideoLinks = new HashMap<>();
        // 固定 protocol 为 "rtmp"
        String protocol = "rtmp";

        try {
            String url ="https://evsretail.bce.baidu.com/api/v2/points/"+pointId+"/signed_url?protocol=rtmp";

            // 生成认证头
            Map<String, String> headerParams = buildAuthHeaderParams("accessKey", "secretKey", "/api/v2/points/"+pointId+"/signed_url");

            // 创建 HTTP 连接
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
            con.setRequestMethod("GET");

            // 设置请求头
            for (Map.Entry<String, String> headerParamEntry : headerParams.entrySet()) {
                con.setRequestProperty(headerParamEntry.getKey(), headerParamEntry.getValue());
            }

            // 获取响应码并检查请求是否成功
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应数据
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析 JSON 响应
                JSONObject jsonResponse = JSON.parseObject(response.toString());

                // 获取播放链接数组
                List<String> urls = jsonResponse.getJSONArray("urls").toJavaList(String.class);
                List<String> mainUrls = jsonResponse.getJSONArray("mainUrls").toJavaList(String.class);
                List<String> subUrls = jsonResponse.getJSONArray("subUrls").toJavaList(String.class);

                // 将数据存入结果映射
                Map<String, List<String>> links = new HashMap<>();
                links.put("urls", urls);
                links.put("mainUrls", mainUrls);
                links.put("subUrls", subUrls);
                pointVideoLinks.put(String.valueOf(pointId),links);
            } else {
                System.out.println("请求失败，响应码: " + responseCode + "，pointId: " + pointId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pointVideoLinks; // 返回所有点位的链接数据
    }

}
